<template>
  <view class="message-detail-page" ref="contentRef" v-if="loadedFlag">
    <view class="message-detail-box">
      <view class="detail-head">
        <view class="detail-item">
          <view class="item-head">
            <view>
              <image
                  class="type-icon"
                  :src="tagList[messageDetailData.detail.msgType]?.src"
              ></image>
              <text class="title">{{ messageDetailData.detail.msgTitle }}</text>
            </view>
            <text
                class="status"
                v-if="
                !['CONFIRMED', 'REJECTED'].includes(
                  getStatusFull(messageDetailData.detail.status)
                )
              "
                :class="{
                toConfirmed:
                  getStatusFull(messageDetailData.detail.status) ==
                  'VIEWED_PENDING_CONFIRMATION',
                confirmed:
                  getStatusFull(messageDetailData.detail.status) == 'CONFIRMED' || getStatusFull(messageDetailData.detail.status) == 'AGREED',
                refuse:
                  getStatusFull(messageDetailData.detail.status) == 'REJECTED',
              }"
            >{{ getStatusLabel(messageDetailData.detail.status) }}
            </text
            >
            <image
                class="status-ack"
                :src="
                getStatusFull(messageDetailData.detail.status) == 'CONFIRMED'
                  ? 'http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/confirm-status.png'
                  : getStatusFull(messageDetailData.detail.status) == 'REJECTED'
                  ? 'http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/refuse-status.png'
                  : null
              "
            ></image>
          </view>
          <view class="item-center">
            {{ messageDetailData.detail.msgDescription }}
          </view>
          <view class="item-bottom">
            <text class="user">{{ messageDetailData.detail.sendName }}</text>
            <view class="time">{{ messageDetailData.detail.date }}
              <text v-if="messageDetailData.detail.autoConfirmTime">·</text>
              <text v-if="messageDetailData.detail.autoConfirmTime">
                {{ messageDetailData.detail.autoConfirmTime }}天后自动确认
              </text>
            </view>
          </view>
        </view>
        <view
            v-if="getStatusFull(messageDetailData.detail.status) == 'REJECTED'"
            class="refuse-row"
        >
          <text class="refuse-row-text">拒绝理由</text>
          <view class="refuse-row-info">
            {{ messageDetailData.detail.opinionInfo }}
          </view>
        </view>
      </view>
      <!--    start file-list-->
      <view class="file-list">
        <view class="file-list__title">已上传文件</view>
        <view class="file-item" v-for="(item,index) in fileList" :key="item.fileId">
          <view class="file-item__left">
            <image v-if="['png','jpg'].includes(item.fileType)" class="file-img" mode="aspectFit"
                   :src="item.url"></image>
            <video class="file-video" v-else-if="['mp4'].includes(item.fileType)" :src="item.url"></video>
            <image v-else class="file-img" mode="aspectFit"
                   src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/default-file-img.png"></image>
            <text
                class="oneEllipsis file-item__text">{{ item.fileName }}
            </text>
          </view>
          <view>
            <wd-icon v-if="[1,2].includes(messageDetailData.detail.status)" @click="deleteFile(index)"
                     name="minus-circle-filled" color="#FF3333" size="18px"></wd-icon>
          </view>
          <view class="file-item__download" @click="copyFileUrl(item.url)"
                v-if="[3,5].includes(messageDetailData.detail.status)">
            <wd-button round type="primary">下载</wd-button>
          </view>
        </view>
        <div class="no-file" v-if="fileList.length===0">暂无数据</div>
      </view>
      <!--    end file-list-->
      <view class="detail-content">
        <view class="detail-content__bg"></view>
        <view class="detail-content__block">
          <view class="gradient-bg"></view>
          <view class="item-row" v-for="item in messageDetailData.list">
            <view class="title">{{ item.title }}</view>
            <!-- 普通文本展示 -->
            <view class="value" v-if="isInputComponent(item?.name)">
              <!--              <text v-if="item?.name" class="name">{{ item?.name }}</text>-->
              <text>{{
                  item?.valueType == "Array" ? item?.value.join(",") : item?.value
                }}
              </text>
            </view>
            <!-- 附件展示 name- 可点击 doc, 压缩包之类 -->
            <view class="value" v-if="item?.name == 'FileUpload'">
              <!--              <text class="name">{{ item?.name }}</text>-->
              <view
                  class="fileUpload"
                  v-if="item?.value.length"
                  v-for="file in item.value"
              >
                <view>
                  <a class="link" @click="openDoc(file?.url)">{{
                      file.fileName
                    }}</a>
                </view>
              </view>
            </view>
            <!-- 视频 -->
            <view class="value" v-if="item?.name == 'VideoUpload'">
              <view v-if="item?.value.length">
                <video
                    id="myVideo"
                    v-for="video in getArray(item.value)"
                    :key="video.id"
                    :src="video"
                    enable-danmu
                    danmu-btn
                    controls
                ></video>
              </view>
            </view>
            <!-- 超链接 -->
            <view class="value" v-if="item?.name == 'HyperlinkInput'">
              <!--              <text class="name">{{ item?.name }}</text>-->
              <view class="link" @click="onClickLink(item)">{{
                  item.value
                }}
              </view>
            </view>
            <!-- 内部超链接 -->
            <view class="value" v-if="item?.name == 'internelinkInput'">
              <!--              <text class="name">{{ item?.name }}</text>-->
              <view class="link" @click="onClickInteriorLink(item)">点击查看详情
              </view>
            </view>
            <!-- 图片 -->
            <view class="value" v-if="item?.name == 'ImageUpload'">
              <!--              <text class="name">{{ item?.name }}</text>-->
              <view class="imageUpload">
                <image
                    v-for="(ite, index) in item.value"
                    :key="index"
                    :src="ite.url"
                    @click="preViewImg(getArray(item.value), index)"
                ></image>
              </view>
            </view>
            <!-- 语言转文本 -->
            <view class="value" v-if="item?.name == 'VoiceToText'">
              <text class="name">{{ item?.value?.txt }}</text>
              <!-- <text class="link" @click="onClickLink(item)">{{item.value?.url}}</text> -->
            </view>
            <!-- 成员选择UserPicker -->
            <view class="value" v-if="item?.name == 'UserPicker'">
              <view v-for="itm in item.value" class="name">
                <text>{{ itm?.type }} - {{ itm?.name }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view
        v-if="
        ['UNREAD', 'VIEWED_PENDING_CONFIRMATION'].includes(
          getStatusFull(messageDetailData.detail.status)
        ) && getTypeFull(messageDetailData.detail.noticeType) !== 'ORDINARY'
      "
        class="detail-btn"
    >
      <view class="upload-file" @click="showUploadFile = true">
        <img class="upload-file__img" src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/upload-icon.png"/>
        <view>上传文件</view>
      </view>
      <button type="info" @click="isPopupVisible = true">拒绝</button>
      <button size="medium" @click="onClickConfirmed(4)">确认</button>
    </view>
    <Popup v-model="isPopupVisible">
      <view
          class="wrapper"
          :class="{ 'popup-show': isPopupVisible }"
          :style="{ bottom: `${keyboardHeight}px` }"
      >
        <view class="wrapper-header">
          <wd-icon name="close" size="22px" @click="closePopup"/>
          <view class="title">拒绝理由</view>
          <text class="confirmed" @click="handleConfirmed(5)">完成</text>
        </view>
        <wd-textarea
            class="textarea"
            v-model="refuseData"
            :maxlength="100"
            show-word-limit
        />
      </view>
    </Popup>
    <wd-message-box custom-class="custom-rate-class"/>
    <!--    start 上传图片-->
    <uploadFile
        v-if="showUploadFile"
        v-model:show-upload="showUploadFile"
        v-model:file-list="fileList"
    ></uploadFile>
    <!--    end 上传图片-->
  </view>
</template>

<script setup>
import {ref, reactive, onMounted, onUnmounted} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import Popup from "@/components/popup/index.vue";
import useUserStore from "@/store/modules/user/index.js";
import {useMessage} from "@/uni_modules/wot-design-uni";
import {confirmedMessage, messageDetail} from "@/api/user";
import {toast} from "../../../utils/utils";
import {aDownFile} from "../../../utils/downFile";
import uploadFile from "./components/uploadFile.vue"

const message = useMessage();
const {tagList, getTypeFull, getStatusFull, getStatusLabel} = useUserStore();
const msgId = ref(null);
onLoad((e) => {
  msgId.value = e?.id;
  getMessageDetailData(e?.id);
});
const messageDetailData = reactive({
  detail: {},
  list: [],
});

const inputComponents = [
  "CascaderInput",
  "DateTime",
  "EditorInput",
  "TextInput",
  "SelectInput",
  "TextareaInput",
  "MultipleSelect",
];
const loadedFlag = ref(false)
const isInputComponent = (name) => {
  return inputComponents.includes(name);
};
const getMessageDetailData = async (msgId) => {
  try {
    const {data} = await messageDetail({
      readMark: true, // 是否已读
      msgId, // 消息id
    });
    const [datePart, timePart] = data.createTime.split(" ");
    messageDetailData.detail = {
      ...data,
      date: datePart,
    };
    messageDetailData.list = JSON.parse(data.msgContent);
    fileList.value = messageDetailData.detail?.attachmentsList ?? []
    fileList.value.map(item => {
      if (!item.fileType) {
        item.fileType = getFileType(item.fileName)
      }
    })
    loadedFlag.value = true
  } catch (error) {
    console.log(error);
  }

};
const isPopupVisible = ref(false);
const refuseData = ref(""); //确认意见或拒绝原因，拒绝消息
const closePopup = () => {
  isPopupVisible.value = false;
  refuseData.value = "";
};
const onClickConfirmed = (type) => {
  message
      .confirm({
        title: "确认该条消息?",
        confirmButtonText: "确认",
        cancelButtonText: "再想想",
      })
      .then(() => {
        handleConfirmed(type);
      });
};
const handleConfirmed = async (type) => {
  try {
    //处理状态 3--已确认，4--已同意，5--已拒绝
    const dealUploadFile = fileList.value.map(item => {
      return {
        accacId: item.fileId,
        msgId: msgId.value,
        url: item.url,
        fileName: item.fileName
      }
    })
    let requestData = {
      msgId: msgId.value, // 消息id
      status: type,
      resourceUrls: dealUploadFile
    };
    const trimmedUsername = refuseData.value.trim();
    if (type == 5) {
      if (!trimmedUsername) {
        return toast("请输入拒绝理由", "none");
      }
      requestData = {
        ...requestData,
        opinionInfo: refuseData.value,
      };
    }
    const res = await confirmedMessage(requestData);
    if (res.code == 200) {
      toast("已提交");
      setTimeout(() => {
        uni.navigateBack();
      }, 300);
    } else {
      toast("提交失败，请稍后再试");
    }
  } catch (error) {
    console.log(error);
  }
};
// 将对象数组转为简单数组
const getArray = (arr) => {
  if (!Array.isArray(arr) || arr.length === 0) {
    return [];
  }
  return arr.map((item) => item.url);
};

// 打开附件
const openDoc = async (fileUrl) => {
  try {
    const localFilePath = await downloadFile(fileUrl);
    uni.openDocument({
      filePath: localFilePath, // 本地文件路径
      // fileType: 'pdf',// 文件类型，默认为空字符串，可根据需要指定，有效值 doc, xls, ppt, pdf, docx, xlsx, pptx，
      showMenu: true, // 显示菜单，用户可以选择保存等操作
      success: function (res) {
        console.log("打开文档成功", res);
      },
      fail: function (err) {
        console.log("打开文档失败", err);
      },
    });
  } catch (error) {
    console.error("处理文件失败", error);
  }
};
const downloadFile = (url) => {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url: url, // 远程文件 URL
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.tempFilePath); // 返回临时文件路径
        } else {
          reject(new Error(`下载文件失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(new Error(`下载文件失败: ${err}`));
      },
    });
  });
};
const getFileType = (fileName) => {
  if (!fileName) return
  const extension = fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);
  return extension;
}

// 预览图片
const preViewImg = (urls, index) => {
  uni.previewImage({
    urls,
    current: index,
  });
};

// 监听键盘高度变化
const keyboardHeight = ref(0);
const onKeyboardHeightChange = (event) => {
  const height = event && event.height ? event.height : 0;
  keyboardHeight.value = height;
};
onMounted(() => {
  uni.onKeyboardHeightChange(onKeyboardHeightChange);
});
// 组件销毁时，注销事件
onUnmounted(() => {
  uni.offKeyboardHeightChange(onKeyboardHeightChange);
});

// 点击附件 下载
const handleFileClick = (file) => {
  aDownFile(file.url, file.fileName);
};
// 点击超链接跳转
const onClickLink = (item) => {
  uni.navigateTo({
    url: `/pages/linkPage/linkPage?title=${item.title}&value=${item.value}`,
  });
};
// 点击超链接跳转
const onClickInteriorLink = (url) => {
  uni.navigateTo({
    url
  });
};

//上传附件
const fileList = ref([])
const showUploadFile = ref(false)
const deleteFile = (index) => {
  fileList.value.splice(index, 1)
}

//下载-复制链接
const copyFileUrl = (url) => {
  uni.setClipboardData({
    data: url,
    success: function () {
      uni.showToast({title: '附件链接已复制成功，建议使用链接在电脑端下载！', icon: 'none'})
    }
  });
}
</script>

<style lang="scss" scoped>
@import "detail";
</style>
